package com.xitang.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xitang.common.bean.BizCategoryProduct;
import com.xitang.common.bean.BizProduct;
import com.xitang.common.bean.BizProductDetail;
import com.xitang.common.dto.PageQueryRsp;
import com.xitang.common.dto.ProductQueryReq;
import com.xitang.common.mapper.BizCategoryProductMapper;
import com.xitang.common.mapper.BizProductDetailMapper;
import com.xitang.common.mapper.BizProductMapper;
import com.xitang.common.service.IProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    protected BizProductMapper productMapper;

    @Autowired
    protected BizProductDetailMapper productDetailMapper;

    @Autowired
    protected BizCategoryProductMapper categoryProductMapper;

    @Override
    public PageQueryRsp<BizProduct> getProductList(ProductQueryReq queryReq) {
        Long totalCount = productMapper.selectCountByCustom(queryReq);
        if (Objects.isNull(totalCount) || totalCount < 1) {
            return new PageQueryRsp<>();
        }
        int pageNo = queryReq.getPageNo();
        int pageSize = queryReq.getPageSize();
        int offset = (pageNo - 1) * pageSize;
        List<BizProduct> bizProducts = productMapper.selectDataByCustom(offset, pageSize, queryReq);
        PageQueryRsp<BizProduct> pageQueryRsp = new PageQueryRsp<>();
        pageQueryRsp.setRecords(bizProducts);
        pageQueryRsp.setTotal(totalCount);
        return pageQueryRsp;
    }

    @Override
    public BizProductDetail getProductDetail(String productCode) {
        BizProductDetail bizProductDetail = productDetailMapper.selectProductAndMaterials(productCode);
        if (Objects.nonNull(bizProductDetail)) {
            bizProductDetail.setProductCode(productCode);
        }
        QueryWrapper<BizCategoryProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_code", productCode);
        List<BizCategoryProduct> bizCategoryProducts = categoryProductMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(bizCategoryProducts)) {
            bizProductDetail.setCategoryCode(bizCategoryProducts.get(0).getCategoryCode());
        }
        return bizProductDetail;
    }
}
